package com.level.base;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 
 */
public class BaseController {
    /**
     * 下载文件
     *
     * @param file
     * @param response
     * @throws Exception
     */
    public void downloadFile(File file,HttpServletResponse response) throws Exception {
        InputStream fis = null;
        OutputStream toClient = null;
        try {
            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 清空response
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            toClient.write(buffer);
            toClient.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (null != fis) {
                fis.close();
            }
            if (null != toClient) {
                toClient.close();
            }
        }

    }

    /**
     * 下载文件
     *
     * @param bytes
     * @param response
     * @param name
     * @throws Exception
     */
    public void downloadFile(byte[] bytes,HttpServletResponse response,String name) throws Exception {
        InputStream fis = null;
        OutputStream toClient = null;
        try {
            // 清空response
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(name,"UTF-8"));
            toClient.write(bytes);
            toClient.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (null != fis) {
                fis.close();
            }
            if (null != toClient) {
                toClient.close();
            }
        }

    }
}
